<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import axios from 'axios';
import { ChatRound, Share, Upload, Close, User } from '@element-plus/icons-vue';

const videoList = ref([]); // 维护所有已加载的视频
const currentIndex = ref(0);
const showScrollHint = ref(true);
const scrollLock = ref(false);
const errorMsg = ref('');
const loadedVideoIds = ref([]); // 记录已加载的视频ID，用于去重
const showUploadDialog = ref(false);
const selectedFile = ref(null);
const uploadProgress = ref(0);
const uploadSuccess = ref(false);
const uploadError = ref('');

axios.defaults.baseURL = 'http://localhost:8040';
const videoRefs = ref([]);

// 监听currentIndex变化，实现视频自动切换播放状态
watch(currentIndex, (newIndex, oldIndex) => {
  // 暂停上一个视频
  if (oldIndex !== null && videoRefs.value[oldIndex]) {
    videoRefs.value[oldIndex].pause();
  }

  // 当滚动到接近列表末尾时，提前加载下一个视频
  if (newIndex >= videoList.value.length - 2) {
    loadMoreVideos();
  }

  // 播放当前视频 - 修复并完善自动播放逻辑
  if (videoRefs.value[newIndex]) {
    const playVideo = async () => {
      try {
        // 先尝试直接播放
        await videoRefs.value[newIndex].play();
      } catch (err) {
        console.warn('自动播放失败，尝试用户交互后播放:', err);
        // 可以在这里显示一个播放按钮提示用户点击
        showPlayPrompt.value = true;

        // 5秒后隐藏提示
        setTimeout(() => {
          showPlayPrompt.value = false;
        }, 5000);
      }
    };

    // 确保视频元数据已加载
    if (videoRefs.value[newIndex].readyState >= 2) {
      playVideo();
    } else {
      // 监听元数据加载完成事件
      videoRefs.value[newIndex].addEventListener('loadedmetadata', playVideo, { once: true });
    }
  }
});

// 切换视频播放/暂停状态
const toggleVideoPlay = (index) => {
  const video = videoRefs.value[index];
  if (video) {
    if (video.paused) {
      video.play().catch(err => {
        console.warn('播放失败，可能由于浏览器限制:', err);
      });
    } else {
      video.pause();
    }
  }
};

// 获取随机视频
const fetchRandomVideo = async (excludeIds = []) => {
  try {
    const excludeIdsStr = excludeIds.join(',');
    const res = await axios.get(`/video/random?excludeIds=${excludeIdsStr}`);

    if (res.data.code === 200 && res.data.data) {
      return res.data.data;
    } else if (res.data.code === 200 && !res.data.data) {
      errorMsg.value = '';
      return null;
    } else {
      errorMsg.value = `获取视频失败：${res.data.msg || '未知错误'}`;
      return null;
    }
  } catch (error) {
    errorMsg.value = `请求错误：${error.message}`;
    console.error('获取随机视频失败:', error);
    return null;
  }
};

// 初始加载视频
const initVideos = async () => {
  try {
    // 初始加载3个视频，保证有足够的内容可以滚动
    for (let i = 0; i < 1; i++) {
      await loadMoreVideos();
    }
  } catch (error) {
    console.error('初始化视频失败:', error);
  }
};

// 加载更多视频
const loadMoreVideos = async () => {
  const newVideo = await fetchRandomVideo(loadedVideoIds.value);
  if (newVideo) {
    videoList.value.push({ ...newVideo, liked: false });
    loadedVideoIds.value.push(newVideo.videoId);
    errorMsg.value = '';
  }
};

const handleScroll = (e) => {
  if (scrollLock.value) return;
  scrollLock.value = true;
  setTimeout(() => scrollLock.value = false, 500);
  showScrollHint.value = false;

  const deltaY = e.deltaY;
  // 向下滚动
  if (deltaY > 0) {
    // 如果已经是最后一个视频，先加载新视频再滚动
    if (currentIndex.value >= videoList.value.length - 1) {
      loadMoreVideos().then(() => {
        currentIndex.value++;
      });
    } else if (currentIndex.value < videoList.value.length - 1) {
      currentIndex.value++;
    }
  }
  // 向上滚动
  else if (deltaY < 0 && currentIndex.value > 0) {
    currentIndex.value--;
  }
};

const toggleLike = (index) => {
  videoList.value[index].liked = !videoList.value[index].liked;
  videoList.value[index].likes += videoList.value[index].liked ? 1 : -1;
};

// 处理文件选择
const handleFileChange = (e) => {
  const file = e.target.files[0];
  if (file) {
    selectedFile.value = file;
    uploadError.value = '';
  }
};

// 上传视频
const uploadVideo = async () => {
  if (!selectedFile.value) return;

  const formData = new FormData();
  formData.append('video', selectedFile.value);
  formData.append('title', '视频标题'); // 实际应用中应该让用户输入
  formData.append('description', '视频描述'); // 实际应用中应该让用户输入

  try {
    uploadProgress.value = 0;
    const res = await axios.post('/video/upload', formData, {
      onUploadProgress: (progressEvent) => {
        uploadProgress.value = Math.round((progressEvent.loaded / progressEvent.total) * 100);
      }
    });

    if (res.data.code === 200) {
      uploadSuccess.value = true;
      uploadError.value = '';
      // 上传成功后刷新视频列表，将新视频添加到最前面
      setTimeout(() => {
        showUploadDialog.value = false;
        uploadSuccess.value = false;
        selectedFile.value = null;
        uploadProgress.value = 0;
        // 重新获取一个新视频并添加到当前位置
        fetchRandomVideo(loadedVideoIds.value).then(newVideo => {
          if (newVideo) {
            videoList.value.splice(currentIndex.value + 1, 0, { ...newVideo, liked: false });
            loadedVideoIds.value.push(newVideo.videoId);
            currentIndex.value++;
          }
        });
      }, 1500);
    } else {
      uploadError.value = res.data.msg || '上传失败';
    }
  } catch (error) {
    uploadError.value = `上传失败：${error.message}`;
    console.error('视频上传错误:', error);
  }
};

const saveVideoState = () => {
  if (videoRefs.value[currentIndex.value]) {
    localStorage.setItem('lastVideoState', JSON.stringify({
      index: currentIndex.value,
      time: videoRefs.value[currentIndex.value].currentTime,
      paused: videoRefs.value[currentIndex.value].paused
    }));
  }
};

const restoreVideoState = () => {
  const savedState = localStorage.getItem('lastVideoState');
  if (savedState) {
    const { index, time, paused } = JSON.parse(savedState);
    // 恢复视频索引
    currentIndex.value = index;

    // 延迟恢复播放位置，确保视频已加载
    setTimeout(() => {
      if (videoRefs.value[index]) {
        videoRefs.value[index].currentTime = time;
        if (!paused) {
          videoRefs.value[index].play().catch(err => {
            console.warn('恢复播放失败:', err);
          });
        }
      }
    }, 500);
  }
};

onMounted(() => {
  initVideos().then(() => {
    // 初始化完成后尝试恢复状态
    restoreVideoState();
  });
  const timer = setTimeout(() => showScrollHint.value = false, 3000);

  // 页面离开时保存状态
  window.addEventListener('beforeunload', saveVideoState);

  onUnmounted(() => {
    clearTimeout(timer);
    window.removeEventListener('beforeunload', saveVideoState);
    // 组件卸载时保存状态
    saveVideoState();
  });
});

const getVideoType = (videoUrl) => {
  if (videoUrl.endsWith('.mp4')) return 'video/mp4';
  if (videoUrl.endsWith('.webm')) return 'video/webm';
  if (videoUrl.endsWith('.avi')) return 'video/avi';
  if (videoUrl.endsWith('.mpeg')) return 'video/mpeg';
  return 'video/mp4'; // 默认MP4格式
};
</script>

<template>
  <div class="short-video-app" @wheel.prevent="handleScroll">
    <!-- 右上角个人中心 -->
    <router-link :to="{name:'videoperson'}">
    <div class="publish-button" @click="showUploadDialog = true">
      <el-icon><User /></el-icon>
    </div>
    </router-link>

    <!-- 主视频内容 -->
    <div class="video-container" :style="{ transform: `translateY(-${currentIndex * 100}vh)` }">
      <div v-for="(item, index) in videoList" :key="item.videoId" class="video-item">
        <div class="video-content">
          <video
              :src="item.videoUrl"
              class="video-player"
              controls
              loop
              playsinline
              preload="auto"
              :type="getVideoType(item.videoUrl)"
              :ref="el => videoRefs[index] = el"
              @click="toggleVideoPlay(index)"
              @ended="handleVideoEnded(index)"
          @loadeddata="handleVideoLoaded(index)"  
          ></video>

        </div>

        <div class="video-info">
          <p class="video-description">{{ item.description }}</p>
          <div class="video-progress-container">
            <div
                class="video-progress-bar"
                :style="{ width: (videoRefs[index]?.currentTime / videoRefs[index]?.duration) * 100 + '%' }"
            ></div>
          </div>
          <div class="video-actions">
            <div class="user-info">
              <img
                  :src="item.pictureUrl"
                  alt="用户头像"
                  class="user-avatar"
              >
              <span class="username">{{ item.videoUsername}}</span>
            </div>
            <div class="action-button" @click="toggleLike(index)">
              <el-icon :size="28" :color="item.liked ? 'red' : ''">
                <HeartFilled v-if="item.liked" />
                <Heart v-else />
              </el-icon>
              <span>{{ item.likes }}</span>
            </div>
            <div class="action-button">
              <el-icon :size="28"><ChatRound /></el-icon>
              <span>{{ item.comments }}</span>
            </div>
            <div class="action-button">
              <el-icon :size="28"><Share /></el-icon>
              <span>分享</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="scroll-hint" v-if="showScrollHint">
      <el-icon :size="32" class="scroll-icon"><ChevronDown /></el-icon>
      <p>向下滑动查看更多</p>
    </div>

    <!-- 错误提示 -->
    <div v-if="errorMsg" class="error-message">
      {{ errorMsg }}
    </div>
  </div>
</template>

<style scoped>
.short-video-app {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  position: relative;
  background-color: #000;
}

.video-container {
  height: 100%;
  transition: transform 0.5s ease;
}

.video-item {
  width: 100vw;
  height: 100vh;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.video-content {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 改为contain保证视频完整显示 */
  background-color: #000;
}

.video-info {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: clamp(15px, 5vw, 20px);
  color: white;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
  box-sizing: border-box;
}


.video-description {
  font-size: clamp(14px, 4vw, 16px);
  margin-bottom: clamp(5px, 2vw, 20px);
  max-width: 80%;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.video-actions {
  display: flex;
  gap: clamp(10px, 5vw, 20px);
}

.action-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: transform 0.2s;
}

.action-button:hover {
  transform: scale(1.1);
}

.action-button span {
  margin-top: 5px;
  font-size: clamp(12px, 3vw, 14px);
}

.scroll-hint {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  color: white;
  background-color: rgba(0, 0, 0, 0.3);
  padding: clamp(10px, 3vw, 15px) clamp(20px, 6vw, 25px);
  border-radius: 30px;
  backdrop-filter: blur(5px);
  transition: opacity 0.5s, visibility 0.5s;
}

.scroll-icon {
  animation: bounce 2s infinite;
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-20px);
  }
  60% {
    transform: translateY(-10px);
  }
}



.error-message {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: #ff4444;
  color: white;
  padding: 10px 20px;
  border-radius: 4px;
  z-index: 1000;
}


/* 发布按钮样式 */
.publish-button {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 100;
  background-color: #181818;
  color: white;
  border: none;
  border-radius: 20px;
  padding: 8px 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: clamp(12px, 3vw, 14px);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  transition: background-color 0.3s;
}

.publish-button:hover {
  background-color: #66b1ff;
}

/* 上传对话框样式 */
.upload-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  width: 90%;
  max-width: 500px;
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
}

.dialog-header {
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-icon {
  cursor: pointer;
  color: #999;
}

.close-icon:hover {
  color: #333;
}

.upload-body {
  padding: 20px;
}

.file-input {
  display: none;
}

.file-label {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  border: 2px dashed #ddd;
  border-radius: 8px;
  cursor: pointer;
  transition: border-color 0.3s;
  color: #666;
}

.file-label:hover {
  border-color: #409eff;
}

.file-info {
  margin-top: 20px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 14px;
}

.progress-bar {
  margin-top: 20px;
  height: 8px;
  background-color: #eee;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.progress {
  height: 100%;
  background-color: #409eff;
  transition: width 0.3s;
}

.progress-bar span {
  position: absolute;
  right: 10px;
  top: -20px;
  font-size: 12px;
  color: #666;
}

.upload-status {
  margin-top: 20px;
  padding: 10px;
  border-radius: 4px;
  font-size: 14px;
  text-align: center;
}

.success {
  background-color: #f0f9eb;
  color: #52c41a;
}

.error {
  background-color: #fff2f0;
  color: #f5222d;
}

.dialog-footer {
  padding: 16px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn, .upload-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  border: 1px solid #ddd;
}

.cancel-btn {
  background-color: white;
  color: #666;
}

.cancel-btn:hover {
  background-color: #f5f5f5;
}

.upload-btn {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.upload-btn:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.video-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-avatar {
  width: clamp(32px, 8vw, 40px);
  height: clamp(32px, 8vw, 40px);
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid white;
}

.username {
  font-size: clamp(14px, 3.5vw, 16px);
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.action-buttons-group {
  display: flex;
  gap: 20px;
}

.action-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: transform 0.2s;
}

.video-progress-container {
  width: 100%;
  height: 4px;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
  margin: 10px 0 15px;
  overflow: hidden;
  cursor: pointer;
}

.video-progress-bar {
  height: 100%;
  background-color: #ff4444;
  transition: width 0.1s linear;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .video-actions {
    gap: 15px;
  }

  .scroll-hint {
    padding: 10px 20px;
  }

  .dialog-content {
    width: 95%;
  }
}

/* 针对小屏幕手机的调整 */
@media (max-width: 375px) {
  .video-info {
    padding: 15px 10px;
  }

  .action-button {
    transform: scale(0.9);
  }
}
</style>